<template>
  <div>
    <el-tree
      :data="data"
      show-checkbox
      node-key="id"
      :default-expanded-keys="treeAn"
      :default-checked-keys="rids"
      :props="defaultProps"
      empty-text="正在加载中"
      @check="treeChange"
    />
    <el-row type="flex" justify="end" style="margin-bottom: -10px; margin-top: 40px">
      <el-button @click="$emit('update:tableAuthority', false)">取消</el-button>
      <el-button type="primary" @click="onChanges">确定</el-button>
    </el-row>
  </div>
</template>

<script>
import { tableTree, tableRids } from '@/api/table'

export default {
  name: 'TableAuthority',
  components: {},
  props: {
    AuthorityList: {
      type: Object,
      default: () => {}
    },
    tableAuthority: {
      type: Boolean,
      required: true
    }

  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      treeAn: [], // 默认展开数组
      rids: [], // 默认选中数组
      childrensIds: []
    }
  },
  computed: {}, // 计算属性
  watch: {
  },
  created() {
    this.tableTree()
  },
  mounted() {},
  methods: {
    async tableTree() {
      this.treeAn = []
      const { data } = await tableTree('tree')
      this.treeDefault(this.AuthorityList.children)
      this.treeData(data.data)
      this.data = data.data
    },
    // 处理id
    treeData(data) {
      data.forEach(item => {
        if (item.children) {
          this.treeAn.push(item.id)
          this.treeData(item.children)
        }
      })
    },
    treeDefault(data) {
      data.forEach(item => {
        item.children ? this.treeDefault(item.children) : this.rids.push(item.id)
      })
    },
    treeChange(data, typedata) {
      this.childrensIds = typedata.halfCheckedKeys
      this.rids = typedata.checkedKeys
    },
    async onChanges() {
      const id = this.AuthorityList.id
      console.log(this.childrensIds)
      console.log(this.rids)
      console.log([...this.childrensIds, ...this.rids])
      const rids = [...this.childrensIds, ...this.rids].join(',')
      console.log(rids)
      try {
        await tableRids(id, { rids })
        this.$emit('tableRoles')
        this.$emit('update:tableAuthority', false)
      } catch (error) {
        console.log(error)
      }
    },
    abc(a, b, c) {
      // console.log(a, b, c)
    }
  }
}
</script>

<style scoped>

</style>
